Skip to content

gh-154675: Avoid importing inspect when creating a slotted dataclass - #156841

Open
aisk wants to merge 2 commits into
python:mainfrom
aisk:dataclasses-inline-unwrap
Open

gh-154675: Avoid importing inspect when creating a slotted dataclass#156841
aisk wants to merge 2 commits into
python:mainfrom
aisk:dataclasses-inline-unwrap

Conversation

@aisk

@aisk aisk commented Sep 2, 2026

Copy link
Copy Markdown
Member

Using @dataclass(slots=True) always imports inspect, just for the single inspect.unwrap() call in _add_slots().

typing and annotationlib already inline the same __wrapped__ walk to avoid the import, so dataclasses can too. Perhaps in the future unwrap() could move into a small private module that inspect and all these copies import, so the implementations do not drift apart.

Importing a module that defines one slotted dataclass, best of 30 runs.

$ cat app.py
from dataclasses import dataclass

@dataclass(slots=True)
class Point:
    x: int = 0
    y: int = 0

$ ./python -c 'import time; t = time.perf_counter(); import app; print(time.perf_counter() - t)'
0.022856871997646522   # before
0.010011243997723795   # after

About 2.3x faster.

@eendebakpt

Copy link
Copy Markdown
Contributor

typing and annotationlib already inline the same __wrapped__ walk to avoid the import, so dataclasses can too. Perhaps in the future unwrap() could move into a small private module that inspect and all these copies import, so the implementations do not drift apart.

Adding another copy to be kept in sync is not very appealing, so I would be in favor of checking whether the private module idea can work. (note that typing and annotationlib use a set for the memo instead of a dict, which can potentially lead to issues when ids are reused).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants